package http

import (
	"gitee.com/flycash/simple-im/internal/domain"
	"gitee.com/flycash/simple-im/internal/service"
	"github.com/ecodeclub/ekit/slice"
	"github.com/ecodeclub/ginx"
	"github.com/gin-gonic/gin"
)

type MessageHandler struct {
	svc service.MessageService
}

func NewMessageHandler(svc service.MessageService) *MessageHandler {
	return &MessageHandler{
		svc: svc,
	}
}

func (h *MessageHandler) PrivateRoutes(server *gin.Engine) {
	message := server.Group("/message")
	message.POST("/history", ginx.B[HistoryMessageReq](h.HistoryMessages))
}

func (h *MessageHandler) HistoryMessages(ctx *ginx.Context, req HistoryMessageReq) (ginx.Result, error) {
	list, err := h.svc.HistoryMessages(ctx, req.ChannelID, req.LastMsgID, req.Offset, req.Limit)
	if err != nil {
		return systemErrorResult, nil
	}
	return ginx.Result{
		Data: slice.Map(list, func(idx int, src domain.Message) Message {
			return Message{
				ID:          src.ID,
				Key:         src.Key,
				Cid:         src.Cid,
				ContentType: src.ContentType,
				Content:     src.Content,
				Sender:      src.Sender,
				SendTime:    src.SendTime,
			}
		}),
	}, nil
}
